package com.gdit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdit.entity.Permissions;
import com.gdit.entity.PermissionsRole;
import com.gdit.entity.Role;
import com.gdit.entity.User;
import com.gdit.mapper.PermissionsMapper;
import com.gdit.mapper.PermissionsRoleMapper;
import com.gdit.mapper.RoleMapper;
import com.gdit.mapper.UserMapper;
import com.gdit.service.IUserService;
import com.gdit.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author fgba
 * @since 2021-09-07
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PermissionsMapper permissionsMapper;
    @Resource
    private PermissionsRoleMapper permissionsRoleMapper;

    @Override
    public User getUserByUsername(String username) {
        return getOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public String getUserAuthorityInfo(String userId) {
        User user = getById(userId);

        StringBuffer authority = new StringBuffer();
        if (redisUtil.hasKey("GrantedAuthority:" + user.getUserName())) {
            authority.append((String) redisUtil.get("GrantedAuthority:" + user.getUserName()));
        } else {
            List<Role> roles = roleMapper.selectList(new QueryWrapper<Role>().inSql("id", "select role_id from t_user_role where user_id = " + userId));
            if (roles.size() > 0) {
                authority.append(
                        roles.stream()
                                .map(role -> "ROLE_" + role.getCode()).collect(Collectors.joining(",")));
                authority.append(",");
            }
            List<PermissionsRole> permissionsRoles = permissionsRoleMapper.selectList(Wrappers.<PermissionsRole>query().select("DISTINCT permissions_id").in("role_id", roles));

            List<String> permissionsIds = new ArrayList<>();
            permissionsRoles.forEach(permissionsRole -> permissionsIds.add(permissionsRole.getPermissionsId()));
            List<Permissions> permissions = permissionsMapper.selectList(Wrappers.<Permissions>query()
                    .in("id", permissionsIds));

            authority.append(
                    permissions.stream()
                            .map(Permissions::getPerms).collect(Collectors.joining(",")));

            log.info("用户ID - {} ---拥有的权限：{}", userId, authority);
            redisUtil.set("GrantedAuthority:" + user.getUserName(), authority.toString(), 60 * 60);
        }
        return authority.toString();
    }

}
